package main

import (
	"fmt"
	"os"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/pflag"
)

func main() {
	cfgFile := pflag.StringP("config", "c", "", "")
	pflag.Parse()
	if *cfgFile == "" {
		fmt.Printf("must provide config file")
		os.Exit(-1)
	}
	config, err := loadConfig(*cfgFile)
	if err != nil {
		panic(err)
	}
	log.WithFields(log.Fields{"config": config}).Info("load config")

	e := echo.New()
	e.Debug = true

	shipVoyageRepo, err := NewShipVoyageRepo(config.ShipVoyageRepoConfig)
	if err != nil {
		panic(err)
	}

	wharfRepo, err := NewWharfRepo(config.WharfRepoConfig)
	if err != nil {
		panic(err)
	}

	e.Use(func(h echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			cc := &Context{
				Context:        c,
				shipVoyageRepo: shipVoyageRepo,
				wharfRepo:      wharfRepo,
			}
			return h(cc)
		}
	})

	logger := middleware.LoggerWithConfig(middleware.LoggerConfig{})
	e.Use(logger)
	e.Use(middleware.Recover())

	e.POST(fmt.Sprintf("%s/:ship_id/location", config.APIPrefix), voyageUpdator)

	e.Logger.Fatal(e.Start(config.Listen))
}
